//
//  LEESendViewController.swift
//  SinaWeibo
//
//  Created by 李江波 on 2016/11/21.
//  Copyright © 2016年 lijiangbo. All rights reserved.
//

import UIKit
import SVProgressHUD

enum clickComposeBtnType: Int {
    case clickComposeBtnTypePhoto = 100
    case clickComposeBtnTypeMention
    case clickComposeBtnTypeTrend
    case clickComposeBtnTypeEmoticon
    case clickComposeBtnTypeMore
}


class LEESendViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        setupUI()
        
       
    }

    private func setupUI() {
     
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(clickDismiss))
    
        navigationItem.rightBarButtonItem = sendBotton
        
        navigationItem.titleView = titleLable
        
        setupTextView()
        setupToolBar()
        setupCollectionView()
        
        //将toolBar移动到最顶层
        self.view.bringSubview(toFront: stackV)
        //增加键盘的监听通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardFrame(n:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        //监听键盘删除按钮
        NotificationCenter.default.addObserver(self, selector: #selector(deleteBottonClick(n:)), name: NSNotification.Name(KSelectEmoticon), object: nil)
        
    }
     //当视图将要显示的时候 就应该判断是否显示图片选择视图
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        vc.view.isHidden = vc.chooseImages.count == 0
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        textView.becomeFirstResponder()
    }
    
    //MARK: 处理toolBar随键盘上升
    @objc private func keyBoardFrame(n: Notification) {
    
//        print(n)
        let endFrame = n.userInfo?["UIKeyboardFrameEndUserInfoKey"] as! CGRect
        
        let h = -(kUISCRRENH - endFrame.origin.y)
        
        stackV.snp.updateConstraints({ (make) in
            
            make.bottom.equalTo(self.view).offset(h)
        })
        
        UIView.animate(withDuration: 0.25) {
            
            self.view.layoutIfNeeded()
        }
    
    }
    //MARK: 键盘删除按钮
    @objc private func deleteBottonClick(n: Notification) {
    
        print(n)
        if n.object == nil {
            
            textView.deleteBackward()
        }else{
        
            textView.inputEmoticon(emoticon: n.object as! HMEmoticon?)
        }
    }
    
    
    ///移除通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    //MARK: 关闭控制器
    @objc fileprivate func clickDismiss() {
    
        self.view.endEditing(true)
        dismiss(animated: true, completion: nil)
    }
    ///发送按钮
    lazy var sendBotton: UIBarButtonItem = {
        let btn = UIButton(title: "发送", bgImageName: "common_button_orange", bgHighlightImageName: "common_button_orange_highlighted", bgDisbleImageName: "common_button_white_disable", titleColor: UIColor.lightGray)
        
        btn.frame = CGRect(x: 0, y: 0, width: 60, height: 35)
        
        btn.addTarget(self, action: #selector(clickSend), for: .touchUpInside)
        
        let barButton = UIBarButtonItem(customView: btn)
        barButton.isEnabled = false
        return barButton
    }()
    ///中间titleView
    lazy var titleLable: UILabel = {
        let lbl = UILabel()
        lbl.textAlignment = .center
        let userName = LEEOAuthViewModel.shared.userInfo?.name ?? "?你是谁?"
        let title = "发送微博\n" + userName
        lbl.text = title
        
        //一定要设置行数啊！！！
        lbl.numberOfLines = 0
        
        let attributedStr = NSMutableAttributedString(string: title)
        let range = (title as NSString).range(of: userName)
        
        attributedStr.addAttributes([NSFontAttributeName : UIFont.systemFont(ofSize: 14), NSForegroundColorAttributeName : UIColor.orange], range: range)
        
        lbl.attributedText = attributedStr
        lbl.sizeToFit()
        return lbl
    }()
    
    ///placeholder
    lazy var placeLable = UILabel(title: "波波在此，休得放肆", textColor: UIColor.darkGray, font: 18)
    ///输入textView
    lazy var textView: UITextView = {
        
        let textView = UITextView()
        textView.backgroundColor = UIColor.lightGray
        textView.font = UIFont.systemFont(ofSize: 18)
        
        textView.delegate = self
        //拖拽让键盘消失
        textView.alwaysBounceVertical = true
        textView.keyboardDismissMode = .onDrag
        
        return textView
    }()
    
    lazy var stackV: UIStackView = {
        
        let stackV = UIStackView()
        
        //添加按钮
        let imageNames = ["compose_toolbar_picture",
                          "compose_mentionbutton_background",
                          "compose_trendbutton_background",
                          "compose_emoticonbutton_background",
                          "compose_add_background"]
        
        //设置stackView参数
        stackV.axis = .horizontal
        stackV.distribution = .fillEqually
        
        for i in 0..<imageNames.count {
        
            let btn = UIButton()
            btn.setImage(UIImage(named: imageNames[i]), for: .normal)
            btn.backgroundColor = UIColor(white: 0.95, alpha: 1)
            btn.tag = 100 + i
            btn.sizeToFit()
            
            btn.addTarget(self, action: #selector(clickComposeBtn(btn:)), for: .touchUpInside)
            
            stackV.addArrangedSubview(btn)
        }
        
        return stackV
    }()
    ///toolBar按钮点击事件
    @objc private func clickComposeBtn(btn: UIButton) {
    
        let type = clickComposeBtnType.init(rawValue: btn.tag)!
        
        switch type {
        case .clickComposeBtnTypePhoto:
            print("点了照片")
        
        vc.moveToPhotoLibrary()
             
        case .clickComposeBtnTypeMention:
            print("@谁呢")
        case .clickComposeBtnTypeTrend:
            print("点了话题")
        case .clickComposeBtnTypeEmoticon:
            print("点了表情")
            
            textView.inputView = (textView.inputView == nil) ? keyboardEmoticonView : nil
            
            if !textView.isFirstResponder {
                
                textView.becomeFirstResponder()
            }
            //刷新
            textView.reloadInputViews()
            
        case .clickComposeBtnTypeMore:
            print("点了更多")
        
        }
    
    }
    
    lazy var keyboardEmoticonView: HMEmoticonKeyboardView = {
        let keyboardEmoticonView = HMEmoticonKeyboardView(frame: CGRect(x: 0, y: 0, width: 0, height: 220))
        return keyboardEmoticonView
    }()
    
    
    lazy var vc: LEEPictureCollectionController = {
        let flowLayout = UICollectionViewFlowLayout()
        let vc = LEEPictureCollectionController(collectionViewLayout: flowLayout)
        
        flowLayout.itemSize = CGSize(width: cellWidth, height: cellWidth)
        
        flowLayout.sectionInset = UIEdgeInsetsMake(0, PhotoMargin, 0, PhotoMargin)
        
        flowLayout.minimumLineSpacing = PhotoMargin
        flowLayout.minimumInteritemSpacing = PhotoMargin
        
        return vc
    }()

}

extension LEESendViewController {
    
    /// 设置底部工具栏
    fileprivate func setupToolBar() {
    
        view.addSubview(stackV)
        
        stackV.snp.makeConstraints { (make) in
            
            make.left.right.bottom.equalTo(self.view)
            
        }
    }

    fileprivate func setupTextView() {
        
        view.addSubview(textView)
        textView.snp.makeConstraints { (make) in
            
            make.left.right.top.equalTo(self.view)
            make.height.equalTo(200)
        }
        
        textView.addSubview(placeLable)
        
        placeLable.snp.makeConstraints { (make) in
            
            make.top.equalTo(textView).offset(8)
            make.left.equalTo(textView).offset(5)
        }
    }
    //添加照片视图
    fileprivate func setupCollectionView() {
    
        view.addSubview(vc.view)
        self.addChildViewController(vc)
        
        vc.view.snp.makeConstraints { (make) in
            
            make.top.equalTo(textView.snp.bottom)
            make.left.right.bottom.equalTo(self.view)
        }
    }
    
    
    //MARK: 点击发送
    @objc fileprivate func clickSend() {
        
        var urlStr = "https://api.weibo.com/2/statuses/update.json"
        
        let parameters = ["access_token" : LEEOAuthViewModel.shared.access_token,
                          "status" : textView.a()]
        
        if vc.chooseImages.count == 0 {
            //纯文本发送
            LEEHTTPRequst.HTTPShared.request(method: .POST, urlString: urlStr, parameters: parameters, completion:{(response , error) -> () in
                
                if error != nil {
                    SVProgressHUD.showError(withStatus: "怎么就发送失败了，人品不好呢")
                    return
                }
                
                SVProgressHUD.showSuccess(withStatus: "发送成功~真棒")
                
                self.clickDismiss()
            })
        }else{
        
            urlStr = "https://upload.api.weibo.com/2/statuses/upload.json"
            //图片微博二进制数据
            let imgData = UIImagePNGRepresentation(vc.chooseImages.first!)
            
            LEEHTTPRequst.HTTPShared.post(urlStr, parameters: parameters, constructingBodyWith: { (formData) in
                //将需要上传的文件的二进制数据拼接到formdata中
                //withFileData: 需要上传的文件的二进制数据
                //name: 服务器接收的字段 "pic"
                //fileName: 服务器存储的名称, 不过新浪微博的服务器会对用户上传的图片按照自己的规则进行处理
                //mimeType: 标识文件类型
                formData.appendPart(withFileData: imgData!, name: "pic", fileName: "ooooo", mimeType: "application/octet-stream")
                
            }, progress: nil, success: { (_, responseObject) in
                
                SVProgressHUD.showSuccess(withStatus: "发送成功~真棒")
                
                self.clickDismiss()
                
            }, failure: { (_, error) in
                
                print(error)
                SVProgressHUD.showError(withStatus: "照片发送失败了，人品不好呢")
            })
                              
        
        }
        
        
    }
}


extension LEESendViewController : UITextViewDelegate {

    func textViewDidChange(_ textView: UITextView) {
        
        sendBotton.isEnabled = textView.hasText
        placeLable.isHidden = textView.hasText
    }
    
}
